package com.google.code.irouter.portal.client.dashboard.main.center.managers.library.browser.guide.editor.form;

import java.util.List;

import com.google.code.irouter.portal.client.AppConstants;
import com.google.code.irouter.portal.client.rpc.api.ApiResult;
import com.google.code.irouter.portal.client.rpc.api.ApiService;
import com.google.code.irouter.portal.client.rpc.api.ApiServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.form.ComboBox;

public final class Detector extends ComboBox {

	private static final AppConstants CONSTANTS = GWT.create(AppConstants.class);
	
	private final ApiServiceAsync apiService = GWT.create(ApiService.class);

	public Detector() {
		super();
		this.setId(Detector.class.getName());

		this.setFieldLabel(CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_library_browser_guide_editor_form_detector());
		this.setName("detector");
		this.setEditable(false);
		this.setMode(ComboBox.LOCAL);
		this.setSelectOnFocus(true);
		this.setAllowBlank(false);

		SimpleStore store = new SimpleStore(new String[] { "id", "name" }, new String[][] {});
		store.load();
		this.setStore(store);
		this.setValueField("id");
		this.setDisplayField("name");
		this.setValidateOnBlur(false);

		this.addListener(new DetectorListener());
		this.show();
	}
	
	public void load() {
		this.setDisabled(true);
		apiService.loadDetector(
				new AsyncCallback<List<ApiResult>>() {
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub						
					}
					@Override
					public void onSuccess(List<ApiResult> result) {
						getStore().removeAll();
						RecordDef recordDef = new RecordDef(
				                new FieldDef[] { 
				                      new StringFieldDef("id"),
				                      new StringFieldDef("name") 
				                      });
						for (ApiResult api : result) {
				            getStore().add(recordDef.createRecord(new Object[] {api.getId(), api.getName()}));
				         }
						if(getValueAsString().trim().length() > 0)
							setValue(getValueAsString());
						setDisabled(false);
					}					
				}
		);
		
	}

}
